package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	_ "gspeed/bootstrap"
	"gspeed/bootstrap/global"
	"gspeed/routers"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	// 设置开发模式
	gin.SetMode(global.Config.GetString("app.runMode"))
	// 自定义路由
	r := routers.ApiRouter()

	// 启动gin
	var s *http.Server
	go func() {
		s = &http.Server{
			Addr:           ":" + global.Config.GetString("app.port"),
			Handler:        r,
			ReadTimeout:    time.Duration(global.Config.GetInt("httpServer.readTimeout")) * time.Second,
			WriteTimeout:   time.Duration(global.Config.GetInt("httpServer.writeTimeout")) * time.Second,
			MaxHeaderBytes: 1 << 20,
		}
		err := s.ListenAndServe()
		if err != nil && err != http.ErrServerClosed {
			log.Fatalf("s.ListenAndServe error: %v", err)
		}
	}()

	//等待中断信号
	quit := make(chan os.Signal)
	//接收syscall.SIGINT和syscall.SIGTERM信号
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	fmt.Println("Shutting down server...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		fmt.Println("Server forced shutdown", err)
	}
	fmt.Println("Server existing")

}
